package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //登录拦截
        ServerHttpRequest request = exchange.getRequest();
        //1.不需要拦截的请求直接放行
         if(isExcludePaths(request.getPath().toString())){
             return chain.filter(exchange);
         }
        //2需要拦截的，获取令牌，判断令牌是否合法，合法放行，不合法拦截
        String authorization = request.getHeaders().getFirst("Authorization");
        //3、校验token
        try {
            Long userId = null;
            //3合法的话保存令牌，用户信息
            userId = jwtTool.parseToken(authorization);
            System.out.println("用户id："+userId);
            //保存用户信息到微服务的请求头中
            Long finalUserId = userId;
            exchange.mutate().request(builder -> builder.header("userIds", finalUserId.toString())).build();
//           return chain.filter(webExchange);
        } catch (Exception e) {
            //不合法，返回错误信息
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }

    private Boolean isExcludePaths(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
